//
//  GoodsDetailSelectSkuPopView.m
//  ABSallRec
//
//  Created by 我演示 on 2019/11/11.
//  Copyright © 2019 Jerry-Fu. All rights reserved.
//

#import "GoodsDetailSelectSkuPopView.h"
#import "GoodsDetailSelectSkuShowCell.h"
#import "DetailSkuSelectModel.h"
#import "GoodsDetailSlectSkuHeaderTitleView.h"
#import "DetailSkuListModel.h"
#import "DetailSkuPorpertyListModel.h"
#import "DetailSkuCompareModel.h"

#import "GoodsDetailSelectSkuPopViewTopView.h"
#import "GoodsDetailSelectSkuPopViewBottomView.h"



#define widthRation ScreenWidth/375.0

#define kcollectionItemCellString  @"collectionItemString"
#define kcollectionItemHeaderString  @"kcollectionItemHeaderString"
@interface GoodsDetailSelectSkuPopView ()<UICollectionViewDataSource , UICollectionViewDelegateFlowLayout,UICollectionViewDelegate>
/**collectionView*/
@property(nonatomic,strong) UICollectionView *collectionView ;

//  字符串拼接比对

/**dict 选择的dict信息存储 */
@property(nonatomic,strong) NSMutableDictionary *selectPropertyDict ;

/**系统原版的dict信息存储内容*/
@property(nonatomic,strong) NSMutableDictionary *originPropertyDict ;

// 顶部的topView
/**topShowImageView*/
@property(nonatomic,weak) GoodsDetailSelectSkuPopViewTopView *topImageView ;
// 底部的bottomView
/**bottomView*/
@property(nonatomic,weak) GoodsDetailSelectSkuPopViewBottomView *bottomCountView ;
/**消失的按钮*/
@property(nonatomic,weak) UIButton *removeBtn ;


/**查看相似商品的按钮*/
@property(nonatomic,weak) UIButton *examineExampleBtn ;

@end

@implementation GoodsDetailSelectSkuPopView

-(NSMutableDictionary *)selectPropertyDict {
    if (!_selectPropertyDict) {
        
        _selectPropertyDict = [NSMutableDictionary dictionary];
    }
    return _selectPropertyDict ;
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.whiteColor;
        
        [_collectionView registerClass:[GoodsDetailSelectSkuShowCell class] forCellWithReuseIdentifier:kcollectionItemCellString];
        [_collectionView registerClass:[GoodsDetailSlectSkuHeaderTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kcollectionItemHeaderString];

    }
    return _collectionView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.whiteColor ;
        [self makeUpUI];
        [self makeUpSubviews];
        
    }
    return  self;
}
-(void)makeUpUI {
    

   
    ///1: topView
    GoodsDetailSelectSkuPopViewTopView *topImageView = [[GoodsDetailSelectSkuPopViewTopView alloc] init];
    topImageView.backgroundColor = [UIColor whiteColor];
    [self addSubview:topImageView];
    self.topImageView = topImageView ;
    
    //0 添加消失按钮选择
    UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [removeBtn setImage:[UIImage imageNamed:@"goodssku_close"] forState:UIControlStateNormal];
    [removeBtn setBackgroundColor:[UIColor whiteColor]];
    [removeBtn addTarget:self action:@selector(pressRemoveBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:removeBtn];
    self.removeBtn = removeBtn;
    
    //2: collectionView
     [self addSubview:self.collectionView];
    
    //3: 添加bottomView
    GoodsDetailSelectSkuPopViewBottomView *bottomView = [[GoodsDetailSelectSkuPopViewBottomView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self addSubview:bottomView];
    self.bottomCountView = bottomView ;
    
    /// 查看相似商品
    UIButton *examineExamBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [examineExamBtn setBackgroundColor:[UIColor colorWithHexString:@"#CC1D32"]];
    [examineExamBtn setTitle:@"确定" forState:UIControlStateNormal];
    [examineExamBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:examineExamBtn];
    self.examineExampleBtn = examineExamBtn;
    
    
}


// 布局控件
-(void)makeUpSubviews {


    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.left.right.equalTo(self).offset(0);
             make.top.equalTo(self).offset(180);
             make.height.offset(150);
         }];
    
        //0: 设置removeBtn
    [self.removeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topImageView.mas_top).offset(10);
        make.right.equalTo(self.mas_right).offset(-10);
        make.width.height.offset(26);
        
    }];
         
         // 布局bottomVIew
         [self.bottomCountView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.left.right.equalTo(self).offset(0);
             make.bottom.equalTo(self).offset(-50);
     //        make.bottom.equalTo(self).offset()
             make.height.offset(50);
         }];
         [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.left.right.equalTo(self).offset(0);
             make.top.equalTo(self.topImageView.mas_bottom).offset(0);
             make.bottom.equalTo(self.bottomCountView.mas_top).offset(0);
         }];
    [self.examineExampleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self).offset(0);
        make.top.equalTo(self.bottomCountView.mas_bottom).offset(0);
    }];
        
}

-(void)setModel:(DetailRootMvvmModel *)model {
    _model = model ;
    /// 数据赋值，或者创建新的model数据类型？？
    // 直接赋值类型信息，
    DetailRootModel *rootModel = model.rootModel ;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for(int i = 0 ; i < rootModel.productSkuPropertyVoList.count ; i++ ) {
        DetailSkuSelectModel *selectModel = rootModel.productSkuPropertyVoList[i];
        [dict setValue:@"" forKey:selectModel.key];
    }
    self.selectPropertyDict = dict ;
    
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
/**分区个数 NSMutableArray <DetailSkuSelectModel *> *productSkuPropertyVoList;*/
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return self.model.rootModel.productSkuPropertyVoList.count ;
}
/**每个分区item的个数*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    DetailRootModel *model = self.model.rootModel ;
    DetailSkuSelectModel *selectModel = model.productSkuPropertyVoList[section];
    return  selectModel.value.count ;
}
/**创建cell */
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    DetailRootModel *model = self.model.rootModel ;
    DetailSkuSelectModel *selectModel = model.productSkuPropertyVoList[indexPath.section];
    DetailSkuSelectShowModel *showModel = selectModel.value[indexPath.row];

    GoodsDetailSelectSkuShowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcollectionItemCellString  forIndexPath:indexPath];
    cell.backgroundColor = [UIColor grayColor];
    cell.showModel  = showModel ;

    return cell;
}
/**创建区头视图和区尾视图 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    DetailRootModel *model = self.model.rootModel ;
    DetailSkuSelectModel *selectModel = model.productSkuPropertyVoList[indexPath.section];
//    DetailSkuSelectModel
    if (kind == UICollectionElementKindSectionHeader){
        GoodsDetailSlectSkuHeaderTitleView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kcollectionItemHeaderString forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.model = selectModel ;
       
        return headerView;
    }
    return nil;
}
/** 点击某个cell*/
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"点击了第%ld分item",(long)indexPath.item);
    DetailRootModel *model = self.model.rootModel ;
    DetailSkuSelectModel *selectModel = model.productSkuPropertyVoList[indexPath.section];
    ///0 : 赋值数据，更新选择的数据，包括互斥与多选处理
    DetailSkuSelectShowModel *showModel = selectModel.value[indexPath.row];
    showModel.isSelected = !showModel.isSelected;
    /// 1 : 首先进行数据的selectNo选择 先去掉之前的选择
    for(DetailSkuSelectShowModel *selectShowModel in selectModel.value) {
        if (selectShowModel != showModel) {
            if ( selectShowModel.isSelected == YES) {
                      selectShowModel.isSelected = NO;
             }
        }else {
            NSLog(@" 点击的是同一个modle");
        }
    }
    ///3： 保存选择的数据 ,由于数据存在互斥，需要判断之前添加的数据是不是被删除掉
    if (showModel.isSelected == YES) {
          [self.selectPropertyDict setValue:showModel.code forKey:selectModel.key];
    }else {
          [self.selectPropertyDict setValue:@"" forKey:selectModel.key];
    }
    
    /// 4：数据验证比对，如果存在，记录对应的sku选择信息
   
    [self compareWithSlectDict];
    [self.collectionView reloadData];
    
}

-(void)compareWithSlectDict {
    
    NSArray *allSelectKeys =  [self.selectPropertyDict allKeys];
    NSInteger   existInteger = 0;
    /// 1: 数据统计，保证全部进行选择，展示对应的商品价格
    for (int i = 0; i< allSelectKeys.count; i++) {
        NSString *codeString  =  [self.selectPropertyDict objectForKey:allSelectKeys[i]];
        if (codeString.length == 0) {
            NSLog(@"codelString ---%@",allSelectKeys[i]);
            // 提示信息
            return;
        }
    }
    //2: 拼接原始的数据
    NSMutableDictionary *originDict = [NSMutableDictionary dictionary];
    NSMutableArray *newModelArray = [NSMutableArray array];
    NSMutableArray *selectModelArray = [NSMutableArray array];
    /// 比对的原版model 信息，原始数据记录
       DetailSkuCompareModel *selectComModel = [[DetailSkuCompareModel alloc] init];
      
    DetailRootModel *listModel = self.model.rootModel;
    for (int i = 0; i<listModel.productSkuInfoList.count ; i++) {
        DetailSkuListModel *proListModel = listModel.productSkuInfoList[i];
        
        DetailSkuCompareModel *skuComModel = [[DetailSkuCompareModel alloc] init];
        /// 再循环数据,1:拼接原始数据
        NSMutableString *prodString = [[NSMutableString alloc] init];
        /// 取出对应的选择的拼接类型
        NSMutableString *selectString = [[NSMutableString alloc] init];
  
        for (int j = 0 ; j < proListModel.productSkuPropertyInfo.count ;j ++) {
            DetailSkuPorpertyListModel *propertyListModel = proListModel.productSkuPropertyInfo[j];
            [prodString appendFormat:@"%@",propertyListModel.code];
            [originDict setValue:prodString forKey:propertyListModel.propertyName];
            
            [selectString  appendFormat:@"%@", [self.selectPropertyDict objectForKey:propertyListModel.propertyName]];
        }
        skuComModel.codeLongString = prodString ;
        skuComModel.skuId = proListModel.ID  ;
        [newModelArray addObject:skuComModel];
        
        selectComModel.codeLongString = selectString ;
        selectComModel.skuId = proListModel.ID ;
//        [selectModelArray addObject:selectComModel];
        
        if ([skuComModel.codeLongString isEqualToString:selectComModel.codeLongString]) {
            
            NSLog(@"数据想扥%@----%@---%@",skuComModel.codeLongString , selectComModel.codeLongString , skuComModel.skuId);
            existInteger ++ ;
            break;
        }else {
//            NSLog(@"没有相等");
        }
    }
    
    //3: 拿到数据，进行处理plist的拼接比对 外部统计，如果程序走到这里还没有比对，那么说明没有库存
    
//    NSLog(@"没有")
    if (existInteger != 0) {
        NSLog(@"存在对应的信息");
    }else {
        NSLog(@"不存在");
    }
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    CGFloat itemW = (kScreenWidth-(kLineNum+1)*kLineSpacing)/kLineNum-0.001;
    DetailRootModel *model = self.model.rootModel ;
    DetailSkuSelectModel *selectModel = model.productSkuPropertyVoList[indexPath.section];
    DetailSkuSelectShowModel *showModel = selectModel.value[indexPath.row];
    
    return CGSizeMake(showModel.itemWidth,30);
}

/**每个分区的内边距（上左下右） insets = {top, left, bottom, right}; */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 10, 15, 10);
}
/** 分区内cell之间的最小行间距*/
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}

// 分区内cell之间的最小列间距

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}
//** 区头大// */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(ScreenWidth, 30);
}
///**
// 区尾大小
// */
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    return CGSizeMake(kScreenWidth, 65);
//}

//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    [self removeFromSuperview];
//}


#pragma mark-事件处理
-(void)pressRemoveBtn {
    [self removeFromSuperview];
}

@end
